const util = require('../../utils/util.js');
const user = require('../../services/user.js');
const audioManager = wx.getBackgroundAudioManager();
Page({
  data: {
    socketopen: false,
    commentlist:[],
    roomNumber:'',
    lessonres: {},
    showTan: false,//弹窗
    showMessage: false,//评论
    showMenu: false,//切换菜单
    showMask: false,//遮罩层 
    commentShow: false,
    showComment: '1',//评论赞赏弹窗切换
    list: [0, 1, 2, 4, 5, 6, 23, 345, 6234, 234, 623, 4, 234, 23, 4, 324],
    //音频相关
    value: 0,
    percent: 0,
    max: 401,
    pass_time: '00:00',
    total_time: '06:41',
    pause: '暂停',
    pause_disable: true,
    audioInfo: true,
    playSrc: 'http://p8pho5rm4.bkt.clouddn.com/play.png',
    pauseSrc: 'http://p8pho5rm4.bkt.clouddn.com/pause.png',
    title:'',
    lessonid:0
  },
  onLoad: function (e) {
    //请求课程资源
    this.getlessonres(e.id);
    this.creatsocket(e);//creat socket
    wx.setNavigationBarTitle({
      title: e.title//页面标题为路由参数
    })
    this.setData({
      title: e.title,
      lessonid:e.id
    })
    var that = this
    this.wxzxSlider = this.selectComponent("#wxzxSlider");
    audioManager.onTimeUpdate(function () {
      if (!that.wxzxSlider.properties.isMonitoring) {
        return
      }
      var currentTime = audioManager.currentTime.toFixed(0);
      if (currentTime > that.data.max) {
        currentTime = that.data.max;
      }
      var pass_time = that.secondTransferTime(currentTime);

      that.setData({
        value: currentTime,
        pass_time: pass_time,
        percent: audioManager.buffered / audioManager.duration * 100,
        disabled: false
      })
    })
    audioManager.onWaiting(function () {
      that.setData({ disabled: true })
    })
    audioManager.onEnded(function () {
      that.setData({
        pause: '暂停',
        pause_disable: true,
        value: 0,
        pass_time: '00:00',
        percent: 0,
        disabled: true
      })
    })

  },
  //***页面卸载执行***
  onUnload: function () {
    wx.closeSocket()
  },
  //***创建scoket连接***
  creatsocket: function (e) {
    var that = this;
    wx.connectSocket({
      url: util.socketurl,
    })
    wx.onSocketOpen(function (res) {
      console.log('WebSocket连接已打开！')
      that.setData({//设置连接状态
        socketopen: true
      })
      var userInfo = wx.getStorageSync('userInfo');
      var data = {
        type: 'addUser',
        broadcast: 1, //加入广播 ==》1：进行房间广播， 0：不进行房间广播  
        closebroadcast: 1, //退出广播 ==》1:进行房间广播， 0:不进行房间广播   
        roomName: 'minichat_video' + e.id,
        userId: userInfo.id,
        userName: userInfo.nickname,
        headUrl: userInfo.headurl,
        sendUser: userInfo,
      }
      wx.sendSocketMessage({
        data: JSON.stringify(data)
      })
    })
    wx.onSocketMessage(function (res) {//监听socket收到消息
      that.socketMessage(res.data);
    })
    wx.onSocketClose(function (res) { //监听socket断开连接
      that.setData({
        socketopen: false
      })
      //that.creatsocket(e);
    })
  },
  //***格式化socket收到的数据***
  socketMessage: function (message) {
    console.log(message);
    var messageInfo = JSON.parse(message);
    var that = this;
    if (messageInfo.sendMessage.type == 'lesson_res') {//如果是课程资源消息
      var data = {
        id: 0,
        res_type: messageInfo.sendMessage.res_type,
        teacher_name: messageInfo.sendUser.nickname,
        teacher_headurl: messageInfo.sendUser.headurl,
        res_path: messageInfo.sendMessage.res_path,
        size: messageInfo.sendMessage.size,
        addtime: messageInfo.sendMessage.addtime,
      }
      var lesson_res = this.data.lesson_res;
      lesson_res.push(data);
      console.log(lesson_res);
      that.setData({
        lesson_res: lesson_res
      })
    }
    if (messageInfo.sendMessage.type == 'addUser') {//如果是进入房间消息
      var commentlist = that.data.commentlist;
      commentlist.unshift({
        userid: messageInfo.sendUser.id,
        nickname: messageInfo.sendUser.nickname,
        headurl: messageInfo.sendUser.headurl,
        msg: messageInfo.sendUser.nickname + '进入了课程！'
      })
      that.setData({
        commentlist: commentlist,
        roomNumber: messageInfo.sendMessage.roomNumber
      })
      console.log(commentlist);
    }
    if (messageInfo.sendMessage.type == 'lesson_comment') {//如果是发布的评论信息
      var commentlist = that.data.commentlist;
      commentlist.unshift({
        userid: messageInfo.sendUser.id,
        nickname: messageInfo.sendUser.nickname,
        headurl: messageInfo.sendUser.headurl,
        msg: messageInfo.sendMessage.msg
      })
      that.setData({
        commentlist: commentlist,
      })
    }
  },
  //**发布评论 */
  socketsendmessage: function () {
    //console.log(this.data.sendmessagetext);
    var that = this;
    var userInfo = wx.getStorageSync('userInfo'); //发送soket消息
    var addtimestamp = Math.round(Date.now() / 1000);
    var data = {
      type: 'groupSend',
      roomName: 'minichat_' + that.data.lessoninfo.lesson_id,
      sendUser: userInfo,
      sendMessage: {
        type: 'lesson_comment',
        msg: this.data.sendmessagetext,
        addtime: addtimestamp
      }
    }
    this.setData({
      sendmessagetext: ''
    })
    wx.sendSocketMessage({//发送soket消息
      data: JSON.stringify(data)
    })
  },
  getlessonres: function (lesson_id) {
    let that = this;
    util.request('school/getlessonres', { lesson_id: lesson_id }, 'GET').then(function (res) {
      console.log(res.data);
      if (res.errno === 0) {
        that.setData({
          lessonres: res.data.lessonres,
        });
      }
    });
  },
  // 回到顶部
  goTop() {
    console.log(111)
    wx.pageScrollTo({
      scrollTop: 0
    })
  },
  // 使页面滚动到底部
  goBottom() {
    console.log(222)
    wx.createSelectorQuery().select('#discuss').boundingClientRect(function (rect) {
      wx.pageScrollTo({
        scrollTop: rect.bottom
      })
    }).exec()
  },
  //弹窗显示切换
  openTan(e) {
    let tan = e.currentTarget.dataset.tan
    if (!tan) {
      this.setData({
        showTan: true,
        showMessage: false,//评论
        showMenu: false,//切换菜单
        showMask: false//遮罩层
      })
    } else {
      this.setData({
        showTan: false,
        showMessage: false,//评论
        showMenu: false,//切换菜单
        showMask: false//遮罩层
      })
    }
  },
  //打开评论
  openMessage(e) {
    let tan = e.currentTarget.dataset.mes
    if (!tan) {
      this.setData({
        showMask: true,
        showMessage: true,
        showTan: false,
        showMenu: false
      })
    }
  },
  openMenu(e) {
    let tan = e.currentTarget.dataset.menu
    if (!tan) {
      this.setData({
        showMask: true,
        showMenu: true,
        showTan: false,
        showMessage: false
      })
    }
  },
  //评论赞赏弹窗切换
  commentTap(e) {
    console.log(e)
    let showComment = e.currentTarget.dataset.id
    if (showComment) {
      this.setData({
        showComment: showComment
      })
    } else {
      this.setData({
        showComment: showComment
      })
    }
  },
  //关闭评论
  closeMessage() {
    this.setData({
      showMask: false,
      showMessage: false
    })
  },
  closeMenu() {
    this.setData({
      showMask: false,
      showMenu: false
    })
  },
  closeAll() {
    this.setData({
      showMask: false,
      showMenu: false,
      showTan: false,
      showMessage: false
    })
  },
  showCommentInfo() {
    this.setData({
      commentShow: true
    })
  },
  closeComment() {
    this.setData({
      commentShow: false
    })
  },
  //声音控件start
  secondTransferTime: function (time) {
    if (time > 3600) {
      return [
        parseInt(time / 60 / 60),
        parseInt(time / 60 % 60),
        parseInt(time % 60)
      ]
        .join(":")
        .replace(/\b(\d)\b/g, "0$1");
    } else {
      return [
        parseInt(time / 60 % 60),
        parseInt(time % 60)
      ]
        .join(":")
        .replace(/\b(\d)\b/g, "0$1");
    }
  },
  // 点击slider时调用
  sliderTap: function (e) {
    console.log("sliderTap")
    this.seek()
  },

  // 开始滑动时
  sliderStart: function (e) {
    console.log("sliderStart")
  },

  // 正在滑动
  sliderChange: function (e) {
    console.log("sliderChange")
  },

  // 滑动结束
  sliderEnd: function (e) {
    console.log("sliderEnd")
    this.seek()
  },

  // 滑动取消 （左滑时滑到上一页面或电话等情况）
  sliderCancel: function (e) {
    console.log("sliderCancel")
    this.seek()
  },
  onShareAppMessage: function (res) {
    let that = this
    return {
      title: that.data.title,
      path: 'pages/video/video?id=' + that.data.lessonid + '&title=' + that.data.title,
      imageUrl: that.data.lessonres.lesson_img
    }
  }


})